<?php

class TurmaController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $alunos = array();

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function actionCadastrados($id) {
        if (!$this->hasOpenedPeriodo()) {
            $this->redirect(array('admin'));
        }

        if (isset($_POST['arv'])) {
            $testvar = $_POST['arv'];
            
            $this->removeTurmaLigacoes($id);
            $nomes = $this->getNamesFromString($testvar);
            $this->insertAlunosNaTurma($id, $nomes);
            $this->redirect(array('view', 'id' => $id));
        }


        $this->render('cadastrados', array(
            'model' => $this->loadModel($id),));
    }

    public function insertAlunosNaTurma($id, $alunos) {
        foreach ($alunos as $aluno) {
            $turmaAluno = new TurmaHasAluno;
            $turmaAluno->turma_int = $id;
            $turmaAluno->aluno_id = $aluno->id;
            $turmaAluno->save();
        }
    }

    public function getNamesFromString($string) {
        $rows = explode(',', $string);
        $alunos = array();

        foreach ($rows as $row) {
            $aluno = Aluno::model()->findByAttributes(array('id' => $row));
            if ($aluno != null) {
                $alunos[] = $aluno;
            }
        }

        return $alunos;
    }

    public function removeTurmaLigacoes($id) {
        $turmas = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $id));
        foreach ($turmas as $turma) {
            $turma->delete();
        }
    }

    public function getAlunosMatriculados($turma) {
        $alunosNaTurma = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $turma->id));
        $alunos = array();
        foreach ($alunosNaTurma as $ant) {
            $alunos[] = Aluno::model()->findByAttributes(array('id'=>$ant->aluno_id));
        }
        return $alunos;
    }

    public function getDisponiveisAlunos($turma) {
        $alunos = Aluno::model()->findAll();
        $turmas = Turma::model()->findAllByAttributes(array('unica' => $turma->unica, 'periodo_id' => $turma->periodo_id));
        $alunosReais = array();
        $alunosFinais = array();
        foreach ($turmas as $turma) {
            $alunosNaTurma = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $turma->id));
            foreach ($alunosNaTurma as $alunoNaTurma) {
                $alunosReais[] = Aluno::model()->findByAttributes(array('id' => $alunoNaTurma->aluno_id));
            }
        }

        foreach ($alunos as $aluno) {
            $pertence = false;
            foreach ($alunosReais as $alunoReal) {
                if ($aluno->id == $alunoReal->id) {
                    $pertence = true;
                    break;
                }
            }
            if ($pertence == false) {
                $alunosFinais[] = $aluno;
            }
        }
        return $alunosFinais;
    }

    public function actions() {
        return array(
            'cadastrados' => array(
                'class' => 'CViewAction',
                'defaultView' => 'cadastrados'
            )
        );
    }

    public function findAlunosRecomendados($model) {

        $caracteristicasComClasse = ClasseHasCaracteristica::model()->findAllByAttributes(array('classe_id' => $model->classe_id));
        $caracteristicas = array();
        $alunos = array();
        $position = 0;

        foreach ($caracteristicasComClasse as $caracteristicaClasse) {
            $caracteristicas[$position] = $caracteristicaClasse->caracteristica_id;
            $position++;
        }

        foreach ($caracteristicas as $caract) {
            $alunosComCaracteristica = CaracteristicaAluno::model()->findAllByAttributes(array('caracteristica_id' => caract));
            foreach ($alunosComCaracteristica as $aCC) {
                $aux = Aluno::model()->findByAttributes(array('id' => $aCC->aluno_id));
                if (!array_key_exists($aux->id, $alunos)) {
                    $alunos[$aux->id] = 0;
                } else {
                    $alunos[$aux->id] = $alunos[$aux->id] + 1;
                }
            }
        }

        return $alunos;
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'cadastrados'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        if (!$this->hasOpenedPeriodo()) {
            $this->redirect(array('admin'));
        }
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        if (!$this->hasOpenedPeriodo()) {
            $this->redirect(array('admin'));
        }

        $model = new Turma;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Turma'])) {
            $periodo = Periodo::model()->findByAttributes(array('polo_id' => Yii::app()->session['polo_id'], 'fechado' => '0'));
            $model->attributes = $_POST['Turma'];
            $model->periodo_id = $periodo->id;
            $model->unica = $model->unica == 1 ? 'Sim' : 'Não';
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function hasOpenedPeriodo() {
        if (Periodo::semPeriodosAbertos(Yii::app()->session['polo_id'])) {
            return false;
        }
        return true;
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Turma'])) {
            $model->attributes = $_POST['Turma'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $turma = $this->loadModel($id);
        $turma->deleteData();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('admin'));

//		$dataProvider=new CActiveDataProvider('Turma');
//		$this->render('index',array(
//			'dataProvider'=>$dataProvider,
//		));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Turma('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Turma']))
            $model->attributes = $_GET['Turma'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Turma the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Turma::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Turma $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'turma-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
